/**
 * 
 */
package nl.sportan.samenloop.adapter;

import java.util.ArrayList;

import nl.sportan.samenloop.R;
import nl.sportan.samenloop.communication.PhotoTarget;
import nl.sportan.samenloop.communication.flickr.PhotoDataRetriever;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gmail.yuyang226.flickr.photos.Photo;
import com.gmail.yuyang226.flickr.photos.Size;
import com.gmail.yuyang226.flickr.photosets.Photoset;

/**
 * @author Bram Wiekens
 *
 */
public class PhotosetAdapter extends BaseAdapter {

	private ArrayList<Photoset> photosets;
	private Context context;
	private Handler handler;
	
	public PhotosetAdapter(Context context, ArrayList<Photoset> photosets) {
		this.context = context;
		this.photosets = photosets;
		this.handler = new Handler();
	}
	
	
	public int getCount() {
		return photosets.size();
	}

	public Object getItem(int position) {
		return photosets.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		Photoset ps = photosets.get(position);
		
		Photo p = ps.getPrimaryPhoto();
		String title = ps.getTitle();
		
		RelativeLayout imageLayout;

		imageLayout = (RelativeLayout) LayoutInflater.from(context).inflate(
				R.layout.flickr_short, parent, false);
		
		TextView titleView = (TextView) imageLayout.findViewById(R.id.title);
		titleView.setText(title);
		
		ImageView iv = (ImageView) imageLayout.findViewById(R.id.image);
		// FIXME This is wrong, very wrong!! Change to Thread workers!
		Thread t = new Thread(new PhotoDataRetriever(context, p, Size.SQUARE, new PhotoHolder(iv) , true));
		t.start();
		
		return imageLayout;
	}
	
	private class PhotoHolder implements PhotoTarget {

		private ImageView target;
		
		public PhotoHolder(ImageView target ) {
			this.target = target;
		}
		
		public void setPhoto(Bitmap bitmap) {
			handler.post(new PhotoUpdater(bitmap, target));			
		}
		
	}
	
	
	private class PhotoUpdater implements Runnable {

		private Bitmap bitmap;
		private ImageView target;
		
		public PhotoUpdater(Bitmap bitmap, ImageView target) {
			this.bitmap = bitmap;
			this.target = target;
		}
		
		public void run() {
			target.setImageBitmap(bitmap);
		}

		
	}

}
